package com.duobeiyun.gmstest.work.sample

import android.content.Context
import android.util.Log
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import com.duobeiyun.generamessagesdk.ErrorInfo
import com.duobeiyun.generamessagesdk.ResultCallback
import com.duobeiyun.generamessagesdk.bean.LoginParams
import com.duobeiyun.generamessagesdk.utils.TokenUtils
import com.duobeiyun.gmstest.TestInstance
import com.duobeiyun.gmstest.log.LogOuter
import kotlinx.coroutines.*
import kotlin.coroutines.resume

/**
 * 异步测试用例
 */
open abstract class WorkAsyncMode(appContext: Context, workerParams: WorkerParameters) :
        CoroutineWorker(appContext, workerParams) {
      var TAG = "WorkAsyncMode"
    var number = "enter case number"
    var timeout = 5*1000L
    override suspend fun doWork(): Result {
        setNumber()
        val chooseAll = inputData.getBoolean("chose_all", false)
        var chooseNumber: Array<String>? = null
        if (!chooseAll) {
            chooseNumber = inputData.getStringArray("chose_number")!!
            Log.d(TAG, " ListenableWorker: ${chooseNumber.contentToString()}")
        }
        if (!chooseAll && !chooseNumber?.contains(number)!!) {
            return Result.success()
        }
        return suspendCancellableCoroutine { continuation ->

            runBlocking {
                val job = launch {
                    try {
                        realWork(continuation)

                    } catch (throwable: Throwable) {
                        Log.e(TAG, " throwable: $throwable")
                        continuation.resume(Result.success())
                    }
                }
                delay(timeout)
                if (!continuation.isCompleted){
                    job.cancel()
                    continuation.resume(Result.success())
                }else{
                    Log.d(TAG, " continuation.isCompleted")
                }

            }


        }
    }


    abstract fun setNumber()

    open fun realWork(continuation: CancellableContinuation<Result>) {

    }


//    open fun realWork() {
//        TestInstance.createInstance?.testCase(object : ResultCallback<Void> {
//            override fun onSuccess(responseInfo: Void?) {
//                LogOuter.print("number:$number \t result:${true} \t name:LoginTest ")
//            }
//
//            override fun onFailure(errorInfo: ErrorInfo) {
//                LogOuter.print("number:$number \t result:${false} \t name:LoginTest ")
//            }
//        })
//    }
}


